//------------------------------------------------------------------
//Got-Internet! Simple check if internet connection program. 
//Copyright (C) 2010  Manuel Villarejo
//------------------------------------------------------------------
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

#import "MyAppController.h"

#import "messages.h"


@implementation MyAppController

@synthesize hostname, Internet;

#pragma mark -
#pragma mark Initialisation methods

- (id) init
{
	self = [super init];
	
	preferencesViewHeight = 250;
	NSDictionary *initialValues = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"YES", 
																	   @"YES", 
																	   @"NO", 
																	   @"NO", 
																	   @"0", 
																	   @"0", 
																	   @"YES", 
																	   @"YES",
																	   [@"~/Library/Application Support/SSHTunnel" stringByExpandingTildeInPath], 
																	   //My entries!!!
																	   @"www.google.com",
																	   @"300",
																	   @"NO",
																	   nil] 
															  forKeys:[NSArray arrayWithObjects:@"checkForNewVersion", 
																	   @"useGraphicalEffects",
																	   @"forceSSHVersion2", 
																	   @"useKeychainIntegration", 
																	   @"selectedTransitionType", 
																	   @"selectedTransitionSubtype", 
																	   @"displayIconInDock", 
																	   @"displayIconInStatusBar",
																	   @"applicationSupportFolder",
																	   //My entries!!!
																	   @"publicHost",
																	   @"refreshInterval",
																	   @"runAtStartup",
																	   nil]];
	
	[[NSUserDefaults standardUserDefaults] registerDefaults:initialValues];
	
//	[self createObservers];
	
	return self;
}
- (void) awakeFromNib
{	
	NSLog(@"INFO: Hello!!!");
	NSLog(@"INFO: Got-Internet! (c) Manuel Villarejo.");
	if ([[NSUserDefaults standardUserDefaults] boolForKey:@"displayIconInStatusBar"] == YES)
		[self prepareStatusBarMenu];
	
	
	NSLog(@"INFO: Launghing Timer..");
	NSTimeInterval	refreshInterval	= 	[[NSUserDefaults standardUserDefaults] integerForKey:@"refreshInterval"];	
	[NSTimer scheduledTimerWithTimeInterval:refreshInterval	 target:self  selector:@selector(refresh:) userInfo:nil	repeats:YES];
	NSLog(@"INFO: Timer CREATED");
	
	
//	MVLoginItem *loginItem = [MVLoginItem new];
//	[loginItem bind:@"enabled" toObject:[NSUserDefaults standardUserDefaults] withKeyPath:@"runAtStartup" options:nil];
	NSLog(@"INFO: ALL OK, NIB finished Loading...");
}

#pragma mark -
#pragma mark Observer and Delegates

/*- (void) createObservers 
{
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(performInfoMessage:) 
												 name:AMNewGeneralMessage
											   object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(performInfoMessage:) 
												 name:AMNewErrorMessage
											   object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(resetAndRestart) 
												 name:AMErrorLoadingSavedState 
											   object:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(applyCurrentServerToAllSessions:) 
												 name:AMErrorLoadingSavedState 
											   object:nil];
}
*/

#pragma mark -
#pragma mark Interface Actions
- (void) checkNewVersionOnServerFromUser:(BOOL)userRequest
{
	NSLog(@"Checking for new version of the programm on internet");
	
	NSString *currentVersion		= [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleVersion"];
	NSDictionary *serverVersion		= [NSDictionary dictionaryWithContentsOfURL:[NSURL URLWithString:@"http://antoinemercadal.fr/updates/sshtunnel/versions.plist"]];
	NSNumber *currentMajorVersion	= [NSNumber numberWithInt:[[[currentVersion  componentsSeparatedByString:@"."] objectAtIndex:0] intValue]];
	NSNumber *currentMinorVersion	= [NSNumber numberWithInt:[[[currentVersion  componentsSeparatedByString:@"."] objectAtIndex:1] intValue]];
	NSNumber *remoteMajorVersion	= [NSNumber numberWithInt:[[serverVersion objectForKey:@"Major"] intValue]];
	NSNumber *remoteMinorVersion	= [NSNumber numberWithInt:[[serverVersion objectForKey:@"Minor"] intValue]];
	
	if (([currentMajorVersion intValue] < [remoteMajorVersion intValue]) 
		|| ( ([currentMajorVersion intValue] == [remoteMajorVersion intValue]) 
			&& ([currentMinorVersion intValue] < [remoteMinorVersion intValue])))
	{
		int resp = NSRunAlertPanel([NSString stringWithFormat:@"New version %@.%@ is out!", 
									remoteMajorVersion, remoteMinorVersion],
								   [serverVersion valueForKey:@"Changes"], 
								   @"Download Version", 
								   @"Ignore", 
								   nil);
		
		if (resp == NSAlertDefaultReturn)
			[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[serverVersion objectForKey:@"DownloadURL"]]];
	}
	else if (userRequest)
		NSRunAlertPanel(@"Version Checker", @"You copy of SSHTunnel is actually up-to-date",  @"OK", nil, nil);
}

- (IBAction) openMainWindow:(id)sender
{
	[mainApplicationWindow makeKeyAndOrderFront:nil];
}

- (IBAction) closeMainWindow:(id)sender
{
	[mainApplicationWindow orderOut:nil];
}

- (IBAction)refresh:(id)sender
{
	NSLog(@"Refreshing!!!");
	NSView *actualView=[statusBarItem view];
	
	NSProgressIndicator *progressIndicator = [[[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0.0, 4.0, 16.0, 16.0)] autorelease];
	[progressIndicator setControlSize:NSSmallControlSize];
	[progressIndicator setStyle:NSProgressIndicatorSpinningStyle];
	NSLog(@"** Starting SpiningProggressIndicator...");
	[progressIndicator startAnimation:self];
	
	NSView *spinningView = [[[NSView alloc] initWithFrame:NSMakeRect(0.0, 0.0, 22.0, 22.0)] autorelease];
	[spinningView addSubview:progressIndicator];
	[statusBarItem setView:spinningView];
	
	NSString *currentHostNSString= 	[[NSUserDefaults standardUserDefaults] valueForKey:@"publicHost"];
	NSLog(@"** Current Host: %@", currentHostNSString);	
	NSHost *currentHostNSHost = [NSHost hostWithName:currentHostNSString];
	NSString *publicAddressNSString = [currentHostNSHost address];
	NSLog(@"** PUBLIC IP: %@", publicAddressNSString);	
	if (publicAddressNSString == nil) {
		[self setInternet:NO];
		NSLog(@"** NO INTERNET CONNECTION!");
	}else {
		[self setInternet:YES];
		NSLog(@"** GOT INTERNET!");
	}
	
	sleep(1);
	
	[progressIndicator stopAnimation:self];
	NSLog(@"** Stopping SpiningProggressIndicator...");
	[statusBarItem setView:actualView];
	
	if (Internet) {
		[statusBarItem setImage:[NSImage imageNamed:@"statusGreen.tif"]];
	}else {
		[statusBarItem setImage:[NSImage imageNamed:@"statusRed.tif"]];
	}	
}

#pragma mark -
#pragma mark View management
- (IBAction) displayPreferencesView:(id)sender
{
	[self openMainWindow:nil];
	
	if (![[[mainApplicationWindow contentView] subviews] containsObject:preferencesView])
	{
		NSLog(@"INFO: mainApplicationWindow -> PreferencesView");
		oldWindowFrame = [mainApplicationWindow frame];
		
		if (oldWindowFrame.size.height < preferencesViewHeight)
		{
			NSRect wframe = oldWindowFrame;
			wframe.size.height = preferencesViewHeight;
			[mainApplicationWindow setFrame:wframe display:NO animate:YES];
		}
		
		NSRect currentSize = [[mainApplicationWindow contentView] frame];
		[preferencesView setFrame:currentSize];
		NSView *currentView = [[[mainApplicationWindow contentView] subviews] objectAtIndex:0];
		[[[mainApplicationWindow contentView] animator] replaceSubview:currentView with:preferencesView];
	}else {
		NSLog(@"WARN: mainApplicationWindow contains PreferencesView");
	}

}

- (IBAction) displayAboutView:(id)sender
{
	[self openMainWindow:nil];
	
	if (![[[mainApplicationWindow contentView] subviews] containsObject:aboutView])
	{
		if ([[[mainApplicationWindow contentView] subviews] containsObject:aboutView])
			[mainApplicationWindow setFrame:oldWindowFrame display:YES animate:YES];
		
		NSRect currentSize = [[mainApplicationWindow contentView] frame];
		[aboutView setFrame:currentSize];
		NSView *currentView = [[[mainApplicationWindow contentView] subviews] objectAtIndex:0];
		[[[mainApplicationWindow contentView] animator] replaceSubview:currentView with:aboutView];
	}else {
		NSLog(@"WARN: mainApplicationWindow contains AboutView");
	}
}

- (void) prepareStatusBarMenu
{
	NSStatusBar *statusBar = [NSStatusBar systemStatusBar];
	statusBarItem = [[statusBar statusItemWithLength: NSVariableStatusItemLength] retain];
	
	// launch refresh!!!!
	[self refresh:nil];
	
	NSString *ipAddr = [[[NSHost currentHost] addresses] objectAtIndex:1];
	NSLog(@"** IP form NSHost %@", ipAddr);
	[statusBarMenu insertItemWithTitle:[NSString stringWithFormat:@"Private IP: %@",ipAddr] action:nil keyEquivalent:@"" atIndex:2];
	//[statusBarMenu insertItemWithTitle:@"Public IP:" action:nil keyEquivalent:@"" atIndex:3];
	NSLog(@"** IP form Public %@", nil);
	
	[statusBarItem setEnabled:YES];
	[statusBarItem setMenu:statusBarMenu];

}

-(void)checkConection{
	NSString *currentHostNSString= 	[[NSUserDefaults standardUserDefaults] valueForKey:@"publicHost"];
	NSLog(@"** Current Host: %@", currentHostNSString);	
	NSHost *currentHostNSHost = [NSHost hostWithName:currentHostNSString];
	NSString *publicAddressNSString = [currentHostNSHost address];
	NSLog(@"** PUBLIC IP: %@", publicAddressNSString);	
	if (publicAddressNSString == nil) {
		[self setInternet:NO];
		NSLog(@"** NO INTERNET CONNECTION!");
	}else {
		[self setInternet:YES];
		NSLog(@"** GOT INTERNET!");
	}
}
-(void)changeViews{
	
}


@end
